package com.sync;

/**
 * 学习点1
 * 当num为addI方法内的私有变量时 无线程安全问题
 * 当为HasSalfPrivateNum类的成员变量时 有安全问题 需要在addI方法上加synchronized关键字
 * <p>
 * 学习点2
 * 当创建对象数量为2的时候 则jvm会创建两把锁
 * 运行结果也类似异步进行
 */

/**
 * @author bysun
 */


public class Demo01 {
    public static void main(String[] args) {
        HasSalfPrivateNum hasSalfPrivateNum = new HasSalfPrivateNum();
        HasSalfPrivateNum hasSalfPrivateNum1 = new HasSalfPrivateNum();
        ThreadA threadA = new ThreadA(hasSalfPrivateNum);
        threadA.start();
        ThreadB threadB = new ThreadB(hasSalfPrivateNum1);
        threadB.start();
    }
}

class HasSalfPrivateNum {
    int num = 0;

    synchronized public void addI(String name) {
        try {
            if ("a".equals(name)) {
                num = 100;
                System.out.println("a set over");
                Thread.sleep(3000);
            } else {
                System.out.println("b set over");
                num = 200;
            }
            System.out.println(name + ",num=" + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadA extends Thread {
    private HasSalfPrivateNum hasSalfPrivateNum;

    public ThreadA(HasSalfPrivateNum hasSalfPrivateNum) {
        super();
        this.hasSalfPrivateNum = hasSalfPrivateNum;
    }

    @Override
    public void run() {
        super.run();
        hasSalfPrivateNum.addI("a");
    }
}

class ThreadB extends Thread {
    private HasSalfPrivateNum hasSalfPrivateNum;

    public ThreadB(HasSalfPrivateNum hasSalfPrivateNum) {
        super();
        this.hasSalfPrivateNum = hasSalfPrivateNum;
    }

    @Override
    public void run() {
        super.run();
        hasSalfPrivateNum.addI("b");
    }
}